#!/bin/bash

F=`readlink -f "$0"`
P=`dirname "$F"`
cd $P

# sed 's/0a$//' - cut trailing EOF
SERVER_CFG=`echo 'exec server' | ./tohex.sh | sed 's/0a$//'`
SERVER_CFG_a1=`echo 'exec serva1' | ./tohex.sh | sed 's/0a$//'`
SERVER_CFG_g6=`echo 'exec servg6' | ./tohex.sh | sed 's/0a$//'`
SERVER_CFG_u1=`echo 'exec servu1' | ./tohex.sh | sed 's/0a$//'`
SERVER_CFG_cr=`echo 'exec servcr' | ./tohex.sh | sed 's/0a$//'`
SERVER_CFG_ov=`echo 'exec servov' | ./tohex.sh | sed 's/0a$//'`

SERVER_LOG=`echo 'server_log.txt' | ./tohex.sh | sed 's/0a$//'`
SERVER_LOG_a1=`echo 'serva1_log.txt' | ./tohex.sh | sed 's/0a$//'`
SERVER_LOG_g6=`echo 'servg6_log.txt' | ./tohex.sh | sed 's/0a$//'`
SERVER_LOG_u1=`echo 'servu1_log.txt' | ./tohex.sh | sed 's/0a$//'`
SERVER_LOG_cr=`echo 'servcr_log.txt' | ./tohex.sh | sed 's/0a$//'`
SERVER_LOG_ov=`echo 'servov_log.txt' | ./tohex.sh | sed 's/0a$//'`

BASENAME="samp03svr"

for i in a1 g6 u1 cr ov
do
  filename="$BASENAME-$i"
  echo -n "proccessing $filename... "
  if test ! -r $filename
  then
    echo "skip"
    continue
  fi
  orgname="server-$i-org.txt"
  modname="server-$i-mod.txt"
  binname="server-$i.bin"
  ./tohex.sh < $filename > $orgname

  if test `grep -o "$SERVER_CFG" $orgname | wc -l` -ne 1 # only one occurence
  then
    echo "fail" # bad file
    continue
  fi
  if test `grep -o "$SERVER_LOG" $orgname | wc -l` -ne 4 # 3
  then
    echo "fail" # bad file
    continue
  fi
  # parse ...
  repl=`eval echo \\$SERVER_CFG_$i`
  sed "s/$SERVER_CFG/$repl/" $orgname > $modname
  mv -f $modname $orgname
  repl=`eval echo \\$SERVER_LOG_$i`
  sed "s/$SERVER_LOG/$repl/" $orgname > $modname

  # 
  ./tobin.sh < $modname > $binname
  chmod +x $binname
  echo "done"
done

